#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "ebox_manhole_mpu6050.h"
#include "ebox_manhole_led_7.h"

#define SENSOR_TASK_STACK_SIZE (1024 * 4)
#define SENSOR_TASK_PRIO 25
#define TASK_DELAY 3
#define FLIP_THRESHOLD 100

int g_coverStatus = 0;

/* 按照注释要求补全函数功能代码 */
static int ManholeModuleTask(void)
{
    uint8_t ret;
    MPU6050Data data;
    int X = 0, Y = 0, Z = 0;

    /* MPU6050模块初始化 */
    ret = ManholeInit();
   if(ret != 0){
    printf("ManholeInit failed!\r\n");
    return;
   }
    
    /* 1、从MPU6050获取检测到的加速度数据并打印
       2、如果X、Y和Z方向有一个变化超出阈值FLIP_THRESHOLD，则LED灯亮，否则LED灯灭
       3、周期检测，时间间隔TASK_DELAY
    */
    while(1){
        ret = ManholeReadData(&data);
        if(ret != 0){
            printf("E53_SC2 Read Data!\r\n");
            return;
        }
        printf("\r\nTemperature     is  %d\r\n",(int)data.Temperature);
        printf("Accel[ACCEL_X_AXIS] is  %d\r\n",(int)data.Accel[ACCEL_X_AXIS]);
        printf("Accel[ACCEL_Y_AXIS] is  %d\r\n",(int)data.Accel[ACCEL_Y_AXIS]);
        printf("Accel[ACCEL_Z_AXIS] is  %d\r\n",(int)data.Accel[ACCEL_Z_AXIS]);
        if (X == 0 && Y == 0 && Z == 0) {
        X = (int)data.Accel[ACCEL_X_AXIS];
        Y = (int)data.Accel[ACCEL_Y_AXIS];
        Z = (int)data.Accel[ACCEL_Z_AXIS];
        }else {
            if (X + FLIP_THRESHOLD < data.Accel[ACCEL_X_AXIS] || X - FLIP_THRESHOLD > 
            data.Accel[ACCEL_X_AXIS]  ||
                Y+ FLIP_THRESHOLD < data.Accel[ACCEL_Y_AXIS] || Y - FLIP_THRESHOLD >
            data.Accel[ACCEL_Y_AXIS] || 
            Z + FLIP_THRESHOLD < data.Accel[ACCEL_Z_AXIS] || Z - FLIP_THRESHOLD >
            data.Accel[ACCEL_Z_AXIS]) {
                ManholeLedCtrl(LED_ON);
                printf("Manhole cover flipped, LED ON!\r\n");
                g_coverStatus = 1;
                } else {
                    ManholeLedCtrl(LED_OFF);
                    printf("Manhole cover restored, LED OFF!\r\n");
                    g_coverStatus = 0;
                }
        }
        sleep(TASK_DELAY);
    }
    
    return 0;
    
}

static void ManholeModuleSample(void)
{
    /* Manhole 模块初始化 */
	ManholeLedInit();
    
	/* 设置线程属性 */
    osThreadAttr_t attr;
    attr.name = "ManholeModuleTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = SENSOR_TASK_STACK_SIZE;
    attr.priority = SENSOR_TASK_PRIO;
    /* 创建智慧井盖检测任务 */
    if (osThreadNew((osThreadFunc_t)ManholeModuleTask, NULL, &attr) == NULL) {
        printf("Failed to create ManholeModuleTask!\n");
    }
}

APP_FEATURE_INIT(ManholeModuleSample);

